from flask import Blueprint, render_template, jsonify, session
from app.extensions import db
from ..models.tablemodel import Users, Article, Notification
from utils.model_to_list import model2list
from utils.redis_util import redis_client
from config.settings import NOTIFY_TYPE

api_bp = Blueprint('api', __name__)


@api_bp.route('/api/userdata')
def user_datas():
    users = Users()
    user_raw_data = users.find_all_user()
    userdata = model2list(user_raw_data)
    return jsonify(userdata)


# 最受欢迎的文章和设置为推荐的各5篇文章
@api_bp.route('/api/most_recommend')
def most_recommend():
    articles = Article()
    most, recommend = articles.find_most_recommend()
    most_dict = [{'id': item[0], 'headline': item[1]} for item in most]
    recommend_dict = [{'id': item[0], 'headline': item[1]} for item in recommend]
    return jsonify(most_dict, recommend_dict)


# # 获取未读通知的数量
# @api_bp.route('/api/notifications/count')
# def notification():
#     # 得到所有的未读的通知消息notices
#     notices = Notification().get_notifications_count()
#     return notices

# 通过redis获取未读通知的数量
@api_bp.route('/api/notifications/count')
def unread_count_by_type():
    # 得到所有的未读的通知消息notices
    types = NOTIFY_TYPE  # 通知类型
    userid = session['userid']
    rset = {}
    for k, v in types.items():
        key = f"notify:{userid}:count:{k}"
        # 优先从 Redis 拿
        cnt = redis_client.get(key)  # 获得某类通知在缓存中的未读数量值
        if cnt is None:
            cnt = Notification().get_notifications_count_by_type(is_read=0, userid=userid, type=v)
            redis_client.set(key, cnt, ex=3600 * 24 * 7)  # 一个星期后过期
        rset[k] = int(cnt)
    # print(rset)
    return jsonify(rset)


# 清除未读通知
@api_bp.route('/api/clear/notifications')
def clear_notifications():
    try:
        Notification().clear_all_notification()
        # 清除redis中的值为0
        types = NOTIFY_TYPE  # 通知类型
        userid = session['userid']
        for k, v in types.items():
            key = f"notify:{userid}:count:{k}"
            redis_client.set(key, 0)

        return jsonify({'success': 1})
    except:
        return jsonify({'success': 0})
